package com.avalon.shop.service;

import com.avalon.core.exception.AvalonException;
import com.avalon.core.model.RecordRow;
import com.avalon.core.util.JacksonUtil;
import com.avalon.core.util.ObjectUtils;
import com.avalon.core.util.RestTemplateUtils;
import com.avalon.core.util.StringUtils;
import com.avalon.shop.ShopContext;
import com.avalon.shop.config.ShopConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class ShareService extends BaseService {
    private final WxCheckRecordService wxCheckRecordService;

    public ShareService(ShopConfig shopConfig, ShopContext shopContext,
                        @Lazy WxCheckRecordService wxCheckRecordService) {
        super(shopConfig, shopContext);
        this.wxCheckRecordService = wxCheckRecordService;
    }

    @Override
    protected String getServiceName() {
        return "pet.share";
    }

    public void addShare(Integer userId,
                         String openId,
                         String shareType,
                         List<Integer> petIds,
                         String comment,
                         List<String> images,
                         String video,
                         String sharePrivacyType) {
        log.info("addShare userId: {}, shareType: {}, petIds: {}, comment: {}, images: {}, video: {}",
                userId, shareType, petIds, comment, images, video);
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("shareType", shareType);
        params.put("comment", comment);
        params.put("sharePrivacyType", sharePrivacyType);
        if (ObjectUtils.isNotEmpty(petIds)) {
            List<Map> petIdList = new ArrayList<>();
            Map<String, Object> petIdsMap = null;
            for (Integer petId : petIds) {
                petIdsMap = new HashMap<>();
                petIdsMap.put("petId", petId);
                petIdList.add(petIdsMap);
            }
            params.put("petIds", petIdList);
        }
        params.put("shareCommentType", "image");
        if (ObjectUtils.isNotNull(video)) {
            params.put("video", video);
            params.put("shareCommentType", "video");
        }
        if (ObjectUtils.isNotEmpty(images)) {
            List<Map> imageList = new ArrayList<>();
            Map<String, Object> imageIds = null;
            for (String img : images) {
                imageIds = new HashMap<>();
                imageIds.put("image", img);
                imageList.add(imageIds);
            }
            params.put("images", imageList);
        }
        RecordRow recordRow = addModel(getServiceName(), params);
        Integer id = recordRow.getInteger("id");
        if (ObjectUtils.isNotEmpty(images)) {
            for (String image : images) { // 图片进行审核
                wxCheckRecordService.createShareCheckRecord(id, openId, image);
            }
        }
    }

    public void checkShareState(Integer shareId, String state) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", shareId);
        param.put("state", state);
        updateModel(param);
    }

    public void updateCheckFailState(Integer id) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("state", "fail");
        updateModel(param);
    }


    public List<Map> getRecommendShare(Integer pageNum, Integer pageSize, Integer userId, String state) {
        log.info("getRecommendShare pageNum:{},pageSize:{},userId:{}",
                pageNum, pageSize, userId);

        HashMap<String, Object> param = new HashMap<>();
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        param.put("userId", userId);
        if (StringUtils.isNotEmpty(state)) {
            param.put("state", state);
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/get/recommend/share",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getRecommendShare 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    public List<Map> getHelpShare(Integer pageNum, Integer pageSize, Integer userId, String state) {
        log.info("getHelpShare pageNum:{},pageSize:{},userId:{}",
                pageNum, pageSize, userId);

        HashMap<String, Object> param = new HashMap<>();
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        param.put("userId", userId);
        if (StringUtils.isNotEmpty(state)) {
            param.put("state", state);
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/get/help/share",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getHelpShare 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    public List<Map> getFollowShare(Integer pageNum, Integer pageSize, Integer userId, String state) {
        log.info("getFanShare pageNum:{},pageSize:{},userId:{}",
                pageNum, pageSize, userId);

        HashMap<String, Object> param = new HashMap<>();
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        param.put("userId", userId);
        if (StringUtils.isNotEmpty(state)) {
            param.put("state", state);
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/get/follow/share",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getFanShare 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    public List<Map> getUserShare(Integer pageNum, Integer pageSize, Integer userId,
                                  Integer curUserId, String sharePrivacyType, String state) {
        log.info("getUserShare pageNum:{},pageSize:{},userId:{},sharePrivacyType:{},state:{}",
                pageNum, pageSize, userId, sharePrivacyType, state);

        HashMap<String, Object> param = new HashMap<>();
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        param.put("userId", userId);
        if (ObjectUtils.isNotNull(curUserId)) {
            param.put("curUserId", curUserId);
        }
        if (StringUtils.isNotEmpty(sharePrivacyType)) {
            param.put("sharePrivacyType", sharePrivacyType);
        }
        if (StringUtils.isNotEmpty(state)) {
            param.put("state", state);
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/get/user/share",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getUserShare 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    /**
     * 点赞
     *
     * @param userId
     * @param shareId
     * @param thumbUp
     */
    public void likeShare(Integer userId, Integer shareId, Integer thumbUp) {
        log.info("likeShare userId:{},shareId:{},thumbUp:{}",
                userId, shareId, thumbUp);

        HashMap<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("shareId", shareId);
        param.put("thumbUp", thumbUp);

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/like/share",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {

        } else {
            log.error("getFanShare 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    public Map getShareDetail(Integer shareId, Integer userId) {
        log.info("getShareDetail userId:{},shareId:{}", userId, shareId);

        HashMap<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("shareId", shareId);

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/get/share/detail",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            return JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<Map>() {
            });
        } else {
            log.error("getShareDetail 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    /**
     * 增加评论
     *
     * @param shareId
     * @param userId
     * @param comment
     * @param image
     * @param relayShareCommentId
     * @return
     */
    public Map addShareComment(Integer shareId,
                               Integer userId,
                               String comment,
                               String image,
                               Integer relayShareCommentId) {
        log.info("addShareComment shareId:{},userId:{},comment:{},image:{}," +
                        "relayShareCommentId:{}",
                shareId, userId, comment, image, relayShareCommentId);

        HashMap<String, Object> param = new HashMap<>();
        param.put("shareId", shareId);
        param.put("userId", userId);
        param.put("comment", comment);
        param.put("image", image);
        if (ObjectUtils.isNotNull(relayShareCommentId)) {
            param.put("relayShareCommentId", relayShareCommentId);
        }

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/share/comment/add",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            return JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<Map>() {
            });
        } else {
            log.error("addShareComment 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    /**
     * 评论删除
     *
     * @param shareCommentId
     */
    public void deleteShareComment(Integer shareCommentId) {
        log.info("deleteShareComment shareCommentId:{}", shareCommentId);

        HashMap<String, Object> param = new HashMap<>();
        param.put("commentId", shareCommentId);

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/share/comment/delete",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
        } else {
            log.error("deleteShareComment 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    /**
     * 评论点赞
     *
     * @param shareCommentId 评论id
     * @param userId         用户id
     * @param like           0 取消点赞 1 点赞
     */
    public void shareCommentLike(Integer shareCommentId, Integer userId, Integer like) {
        log.info("ShareCommentLike shareCommentId:{},userId:{},like:{}",
                shareCommentId, userId, like);

        HashMap<String, Object> param = new HashMap<>();
        param.put("commentId", shareCommentId);
        param.put("userId", userId);
        param.put("like", like);

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/share/comment/like",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
        } else {
            log.error("ShareCommentLike 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    /**
     * 获取评论点赞
     *
     * @param shareId
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     */
    public List<Map> getShareComment(Integer shareId,
                                     Integer pageNum,
                                     Integer pageSize,
                                     Integer userId) {
        log.info("getShareComment shareId:{},pageNum:{},pageSize:{}",
                shareId, pageNum, pageSize);

        HashMap<String, Object> param = new HashMap<>();
        param.put("shareId", shareId);
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        param.put("userId", userId);

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/share/comment/get",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getShareComment 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }


    /**
     * 获取子评论
     *
     * @param rootId   父评论id
     * @param pageNum
     * @param pageSize
     * @param userId
     * @return
     */
    public List<Map> getChildShareComment(Integer rootId,
                                          Integer pageNum,
                                          Integer pageSize,
                                          Integer userId) {
        log.info("getChildShareComment shareCommentId:{},pageNum:{},pageSize:{}",
                rootId, pageNum, pageSize);

        HashMap<String, Object> param = new HashMap<>();
        param.put("rootId", rootId);
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        param.put("userId", userId);

        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/share/comment/child/get",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getChildShareComment 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }
}
